﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Linq.Extensions;
using Abp.Logging;
using Abp.UI;
using AutoMapper;
using MyCompanyName.AbpZeroTemplate.Authorization;
using MyCompanyName.AbpZeroTemplate.Entities;
using MyCompanyName.AbpZeroTemplate.IRepositories;
using MyCompanyName.AbpZeroTemplate.ProductApp.Dto;

namespace MyCompanyName.AbpZeroTemplate.ProductApp
{
    [AbpAuthorize(AppPermissions.Pages_Product)]
    public class ProductAppService : AbpZeroTemplateAppServiceBase, IProductAppService
    {
        private IProductRepository _productRepository;
        private IImageRepository _imageRepository;
        public ProductAppService(IProductRepository productRepository,IImageRepository imageRepository)
        {
            _productRepository = productRepository;
            _imageRepository = imageRepository;
        }

        [AbpAuthorize(AppPermissions.Pages_Product_Create)]
        public async Task CreateProductAsync(CreateProductInput input)
        {
            var id=await _productRepository.InsertAndGetIdAsync(new Product()
            {
                Name = input.Name,
                Price = input.Price,
                CategoryId = input.CategoryId
            });
            //商品图片
            await _imageRepository.InsertAsync(new Image()
            {
                Source = input.FileName,
                ProductId = id
            });
        }

        [AbpAuthorize(AppPermissions.Pages_Product_Delete)]
        public async Task DeleteProductAsync(EntityRequestInput<Guid> input)
        {
            try
            {
                var entity = await _productRepository.GetAsync(input.Id);
                await _productRepository.DeleteAsync(entity);
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("商品id无效！", ex);
                throw new UserFriendlyException("商品id无效！");
            }

            
        }

        [AbpAuthorize(AppPermissions.Pages_Product_Edit)]
        public async Task UpdateProductAsync(EditProductInput input)
        {
            if (!input.Id.HasValue)
            {
                throw new UserFriendlyException("商品id无效！");
            }
            var result=await _productRepository.GetAsync(input.Id.Value);
            result.Name = input.Name;
            result.Price = input.Price;
            result.CategoryId = input.CategoryId;
            //删除旧图片
            await _imageRepository.DeleteAsync(a => a.ProductId == input.Id.Value);
            //再添加新图片
            await _imageRepository.InsertAsync(new Image()
            {
                Source = input.FileName,
                ProductId = input.Id.Value
            });
        }

        public async Task<ProductDto> GetProductForEditAsync(EntityRequestInput<Guid> input)
        {
            var result=await  _productRepository.GetAsync(input.Id);
            var image=result.Images.SingleOrDefault();
            return new ProductDto()
            {
                Id = result.Id,
                Name = result.Name,
                Price = result.Price,
                CategoryName = result.Category.Name,
                CategoryId = result.CategoryId,
                FileName = image==null?"":image.Source
            };
        }

        public async Task<PagedResultOutput<ProductDto>> GetProductsAsync(GetProductsInput input)
        {
            var result=_productRepository.GetAll();
            if (!string.IsNullOrWhiteSpace(input.Name))
            {
                result = result.Where(a => a.Name.Contains(input.Name));
            }
            if (input.StartPrice.HasValue)
            {
                result = result.Where(a => a.Price>=input.StartPrice.Value);
            }
            if (input.EndPrice.HasValue)
            {
                result = result.Where(a => a.Price <= input.EndPrice.Value);
            }
            if (input.CategoryId.HasValue)
            {
                result = result.Where(a => a.CategoryId == input.CategoryId.Value);
            }
            int totalCount =await result.CountAsync();
            var list =await result.OrderBy(input.Sorting).PageBy(input).ToListAsync();//分页
            return new PagedResultOutput<ProductDto>(
                totalCount,
                Mapper.Map<List<ProductDto>>(list)
                );
        }
    }
}
